package cn.tedu.order.service;

import cn.tedu.order.entity.Order;
import cn.tedu.order.feign.AccountClient;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.feign.StorageClient;
import cn.tedu.order.mapper.OrderMapper;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private EasyIdClient easyIdClient;
    @Autowired
    private StorageClient storageClient;
    @Autowired
    private AccountClient accountClient;
    @Transactional
    @GlobalTransactional
    @Override
    public void create(Order order) {
//        调用发号器获取订单id
     String s =   easyIdClient.nextId("order_business");
        Long orderId = Long.valueOf(s);
//        临时产生订单id，调用发号器后删除
//        long orderId =Math.abs(new Random().nextLong());
        order.setId(orderId);
        orderMapper.create(order);
//        减少库存
        storageClient.decrease(order.getProductId(), order.getCount());
//        扣减账户
        accountClient.decrease(order.getUserId(), order.getMoney());
    }
}
